<template>
  <view class="content">
    <privacyPopup></privacyPopup>
    <view :style="{'width':'100%'}">
      <view class="search-bgc">
        <view class="city" @click="selectCity">
          <uni-icons color="#fff" size="18" type="location"></uni-icons>
          <view class="">{{city}}</view>
        </view>
        <uni-easyinput placeholderStyle="color:#71b8ff;margin-bottom:27rpx" class='search-input' trim="true"
          confirmType="search" :clearable="false" prefixIcon="search" placeholder="请输入地点" v-model="coords.searchKeyWord"
          @confirm="search('')"></uni-easyinput>
      </view>

      <view style="width:calc(100% - 40px);padding: 10px;">
        <text style="font-size: 28upx;color: #393939;">附近充电柜</text>
        <image src='../../static/filtration.png' :class="filtrateShow ? 'rotate' : '' "
          style='width:20px;height: 20px;float: right;'></image>
        <text style="float: right;color:#858585;font-size: 26upx;height:40rpx;line-height: 40rpx;"
          @click="changeFiltra">{{coords.searchCabinetBinStatus == 1 ? '空闲':'全部'}}</text>
      </view>

      <view v-if="filtrateShow" class='filtration'>
        <view @click="search(0)">
          <image style='width: 33upx;height: 33upx;' src="../../static/all.png"></image>
          <text>全部</text>
        </view>
        <view @click="search(1)">
          <image style='width: 33upx;height: 33upx;' src='../../static/free.png'></image>
          <text>空闲</text>
        </view>
      </view>
    </view>
    <!-- @click="skip(item)" -->
    <view class="content-view" v-for="(item, index) in chargeAddressList" :key='index'>
      <uni-card>
        <view>
          <view class="namecount">
            <view class="name_left">
              <text class='site'>{{item.name}}</text>
              <image v-if="item.cabinetState.signalIntensity"
                style="width: 30rpx; height: 30rpx; position: relative; top: 4rpx;left: 12rpx;"
                :src="signalData[item.cabinetState.signalIntensity]"></image>
              <image v-else style="width: 30rpx; height: 30rpx; position: relative; top: 4rpx;left: 12rpx;"
                src="/static/offLine.png"></image>
            </view>
            <view class="name_right" @click="distance(item)">
              <image class='distanceImg' src='../../static/distanceImg.png'></image>
              <text>{{caculateLL(item.lat,item.lng,coord.lat,coord.lng) | toFixed}}</text>
            </view>
          </view>
          <text class='address'>{{item.address || ''}}</text>
          <view style="padding-top: 20upx;float: left;">
            <image style='width:15px;height: 15px;float: left;margin-top: 3px;' src='../../static/power.png'></image>
            <text style='color:#009900;margin: 0px 10px;float: left;'>空闲:{{item.idleCount}}</text>
            <text style='float: left;margin-bottom: 15px;'>共{{item.binCount}}</text>
          </view>
        </view>
      </uni-card>
    </view>
    <!-- <uni-load-more :status="nomore"></uni-load-more> -->
    <view v-show="isLoadMore && chargeAddressList.length >0">
      <uni-load-more :status="loadStatus"></uni-load-more>
    </view>

    <view class="nodata" v-if="chargeAddressList.length == 0">
      <image class="empty_img" src="/static/empty.png" mode="widthFix"></image>
      <view>暂无充电柜信息</view>
    </view>

    <tabBar :current="0"></tabBar>
  </view>
</template>

<script>
  import {
    mapActions,
    mapState
  } from 'vuex';
  import {
    getMoney
  } from 'components/calculate/calculate.js';
  import moment from '../../components/moment.js';

  import {
    chargingCabinet
  } from '@/api/equip.js';
  import {
    caculateLL
  } from '@/common/main.js';
  import store from "@/store/index.js";
  import tabBar from "@/components/tabBar.vue";
  import privacyPopup from "@/components/privacyPopup.vue";
  export default {
    components: {
      tabBar: tabBar,
      privacyPopup
    },
    data() {
      return {
        searchValue: '',
        city: '',
        filtrateShow: false,
        but: 'but',
        chargeAddressList: [

        ],
        coords: {
          searchKeyWord: '',
          searchCabinetBinStatus: '',
        },
        more: '',
        time: '',
        page: 1, //页码
        size: 10,
        loadStatus: 'loading', //加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
        isLoadMore: false, //是否加载中
        refresh: false, // 下拉刷新标示
        caculateLL: caculateLL,
        signalData: {
          1: "/static/1.png",
          2: "/static/2.png",
          3: "/static/3.png",
          4: "/static/4.png",
          5: "/static/5.png",
        },
      }
    },
    onShow() {
      // uni.hideTabBar();
      this.filtrateShow = false;
      // this.getNearbyCabinet(this.coord);
      // if (!this.time) {
      //   this.time = setInterval(() => {
      //     this.getDataList();
      //   }, 60000)
      // }
      if (!this.coord.lat) {
        this.$store.dispatch("updateCoord");
      }
    },
    computed: {
      ...mapState(['coord'])
    },
    watch: {
      "coord": {
        handler: function(cur, old) {
          this.getDataList();
          this.getCity();
        },
        deep: true, //对象内部的属性监听，也叫深度监听
        immediate: true
      }
    },
    created() {
      let token = uni.getStorageSync('token') || null;
      if (token) {
        this.$store.dispatch("updateUserInfo");
      }
    },
    onHide() {
      clearInterval(this.time);
    },
    onUnload() {
      clearInterval(this.time);
    },
    finish() {
      clearInterval(this.time);
    },
    filters: {
      toFixed(str) {
        if (!str) return;
        let count = str > 1000 ? ((str / 1000).toFixed(2) + 'km') : (str.toFixed(2) + 'm');
        return count;
      }
    },
    methods: {
      ...mapActions(['Login']),
      search(cabinetBinStatus) {
        this.coords.searchCabinetBinStatus = cabinetBinStatus;
        this.filtrateShow = false;
        this.getDataList();
      },
      getCity() {

        let that = this;
        uni.request({
          header: {
            "Content-Type": "application/text"
          },
          //注意:这里的key值需要高德地图的 web服务生成的key  只有web服务才有逆地理编码
          url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' + this.coord.lng + ',' + this.coord
            .lat +
            '&key=280802ed0116fef931dbcf5e7e9278d7&radius=1000&extensions=all',
          success(re) {
            if (re.statusCode == 200) {
              let datas = re.data.regeocode.addressComponent;
              // console.log("获取中文街道地理位置成功", datas)
              that.city = datas.city.length > 0 ? datas.city : datas.province;
            } else {
              console.log("获取信息失败，请重试！")
            }
          }
        });
      },
      selectCity() {
        let that = this;
        uni.chooseLocation({
          success: (res) => {
            let datas = res.address;
            store.commit("setCoord", {
              latitude: res.latitude,
              longitude: res.longitude
            });
            // if (datas.indexOf('省')) {
            //   that.city = datas.substring(datas.indexOf('省') + 1, datas
            //     .indexOf('市'))
            // } else {
            //   that.city = datas.substring(0, datas.indexOf('市'))
            // }
            // that.city = res.name;

          },
          fail(err) {
            console.log(err)
          }
        })
      },
      // 导航
      distance(item) {
        if (!item.lat || !item.lng) {
          this.$Toast.error('暂无位置信息');
          return;
        }
        // this.$Toast.loading('打开位置信息');
        let that = this;
        uni.getLocation({
          type: 'gcj02', //返回可以用于uni.openLocation的经纬度
          success: function(res) {
            const latitude = res.latitude;
            const longitude = res.longitude;
            uni.openLocation({
              latitude: item.lat, //维度
              longitude: item.lng, //经度
              name: item.name, //目的地定位名称
              scale: 15, //缩放比例
              address: item.address, //导航详细地址
              success: function() {}
            });
          },
          fail: (err) => {
            if (err.errMsg.indexOf('频繁调用')) {
              // uni.showToast({
              //   title: '请勿频繁调用',
              //   icon: 'error',
              //   duration: 1500
              // })
            } else {
              uni.showToast({
                title: '请开启定位',
                icon: 'error',
                duration: 1500
              })
            }
          }
        });
      },
      skip(item) {
        uni.navigateTo({
          url: `../rechargeCabinet/rechargeCabinet?code=${item.code}&lat=${this.coord.lat}&lng=${this.coord.lng}&equipid=${item.id}`
        })
      },
      getDataList() {
        this.$Toast.loading('加载中');
        let param = {
          lat: this.coord.lat,
          lng: this.coord.lng,
          pageNum: this.page,
          pageSize: this.size,
          address: this.coords.searchKeyWord ? this.coords.searchKeyWord : '',
          type: this.coords.searchCabinetBinStatus
        };
        chargingCabinet('/selectAll', 'get', param).then(res => {
          if (res.code == 200) {
            let datas = res.data.records;
            datas.forEach(ele => {
              ele.idleCount = ele.cabinetBins.filter(item => item.status == 0).length;
            })
            this.chargeAddressList = this.page == 1 ? datas : this.chargeAddressList.concat(datas);
            if (datas.length < this.size) { //小于size数，停止请求
              this.isLoadMore = true;
              this.loadStatus = 'nomore';
            } else {
              this.isLoadMore = false;
            }
            uni.hideLoading();
          }
          if (this.refresh) {
            uni.stopPullDownRefresh();
            this.refresh = false;
          }
        }).catch(err => {

        })
      },

      changeFiltra() {
        this.filtrateShow = !this.filtrateShow;
      },
      onPullDownRefresh() {
        this.page = 1;
        this.getDataList();
        this.refresh = true;
      },
      onReachBottom() {
        if (!this.isLoadMore) { //此处判断，上锁，防止重复请求
          this.isLoadMore = true;
          this.page++;
          this.getDataList();
        }
      },
      getNearbyCabinet(dataJson) {
        let that = this;
        this.more = 'loading';

        uni.getLocation({
          success: (res) => {
            this.getCity(res.latitude, res.longitude);

            store.commit("setCoord", {
              latitude: res.latitude,
              longitude: res.longitude
            })
          },
          fail: () => {}
        })
      },
    }
  }
</script>
<style>
  page {
    background-color: #f7f7f7;
  }
</style>
<style lang="scss" scoped>
  @import "@/static/css/common.scss";
  @import "@/static/css/main.scss";

  .namecount {
    @include flexLayout(center, space-between);

    .name_right,
    .name_left {
      @include flexLayout(center, flex-start);
    }

    .name_left {
      width: 70%;
      @include exceedFlow(1);
    }
  }

  .uniui-search {
    color: #71b8ff !important;
  }

  .uni-easyinput__content {
    min-height: 54upx !important;
  }

  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-bottom: 160rpx;
  }

  .rotate {
    transform: rotate(180deg)
  }

  .content-view {
    margin: -5px 10px;
  }

  .search-bgc {
    width: 100%;
    background-color: #1977d2;
    color: #fff;
    display: flex;
    align-items: center;
  }

  /deep/ .search-input {
    width: calc(100% - 120px);
    position: relative;
  }

  .city {
    display: flex;
    align-items: center;
    width: 80px;
    height: 36px;
    margin: 10px;
    line-height: 36px;
    font-size: 12px;
  }

  /deep/ .is-input-border {
    border-radius: 25px !important;
    background: #2e8ae5;
    border: 0px !important;
    padding: 0 20upx;
    /* min-height: 25px!important; */
  }

  /deep/ .uni-easyinput__content-input {
    color: #fff
  }

  .but {
    width: 60px;
    float: left;
    line-height: 25px;
    height: 25px;
    text-align: center;
    margin: 10px;
    border: 1px solid #00000029;
  }

  /deep/ .select-filtrate {
    background-color: #199ed8;
  }

  .distanceImg {
    width: 15px;
    height: 15px;
    margin-right: 10rpx;
  }

  .site {
    font-size: 32rpx;
    font-weight: 900;

  }

  .address {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
    float: left;
    margin-bottom: 5px;
  }

  .filtration {
    position: absolute;
    top: 90px;
    right: 20px;
    width: 206upx;
    height: 170upx;
    background: #7d7c7c;
    z-index: 9999;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-width: 90px;
    min-height: 75px;

    view {
      display: flex;
      align-items: center;
      padding: 20upx 0;

      text {
        font-size: 26upx;
        color: #fff;
        margin-left: 26upx;
      }
    }

    view:nth-child(1) {
      border-bottom: 2upx solid #747474;
    }
  }
</style>